package com.loveofsoftware.fotolab;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Region;
import android.view.MotionEvent;
import android.view.View;

public class CardView extends View
{
    public Paint mPaint = null;
    private final Point mSize = new Point();
    private final Point mStartPosition = new Point();
    public String mText = "";
  //Region is bigger than text, hence we have start position
    Region mRegion = new Region();

    public CardView(Context context, Paint paint, String text, int left, int top)
    {
        super(context);
        mPaint = paint;
        mStartPosition.x=left;
        mStartPosition.y=top;
        mText = text;
        mSize.x = mText.length()*6;
        mSize.y = 15;
        setPosition(mStartPosition);
    }

    @Override
    public void onDraw(Canvas canvas)
    {
        canvas.drawText(mText, mStartPosition.x, mStartPosition.y, mPaint);        
    }
    
    public void onDrawTranslated(Canvas canvas, int startX, int startY)
    {
 
        int x = mStartPosition.x-startX;
        int y = mStartPosition.y-startY;
        if(x>=0 && y>=0)
        	canvas.drawText(mText, x, y, mPaint);        
    }

    public final void setPosition(final Point position)
    {
    	int x = position.x - 10;
    	if(x<0)x=0;
    	int y = position.y - 10;
    	if(y<0)y=0;
        mRegion.set(x, y, x + mSize.x, y + y);
    }

    public final Point getPosition()
    {
        Rect bounds = mRegion.getBounds();
        return new Point(bounds.left, bounds.top);
    }

    public final void setSize(int width, int height)
    {
        mSize.x = width;
        mSize.y = height;

        Rect bounds = mRegion.getBounds();
        mRegion.set(bounds.left, bounds.top, bounds.left + width, bounds.top + height);
    }

    public final Point getSize() { return mSize; }

    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
    	   	
        // Is the event inside of this view?
        if(!isSelected() && !mRegion.contains((int)event.getX(), (int)event.getY()))
        {
            return super.onTouchEvent(event);
        }

        if(event.getAction() == MotionEvent.ACTION_DOWN)
        {           
            bringToFront();
            setSelected(true);
            return true;
        }
        else if(event.getAction() == MotionEvent.ACTION_MOVE)
        {
        	 mStartPosition.x = (int)event.getX();
             mStartPosition.y = (int)event.getY();
             setPosition(mStartPosition);
             //invalidate();
            return true;
        }else {
        	if(event.getAction() == MotionEvent.ACTION_UP)
            {
            	setSelected(false);
            }
            return super.onTouchEvent(event);
        }
    }
}
